package com.github.postsanf.yinian.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.AlbumWallAdapter;
import com.github.postsanf.yinian.bean.YNPhoto;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.service.AlbumContentService;
import com.github.postsanf.yinian.utils.WrapContentGridLayoutManager;
import com.github.postsanf.yinian.view.SpacesItemDecoration;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.HeaderSpanSizeLookup;
import com.github.postsanf.yinian.ynlist.YNRecyclerViewAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class TransferActivity extends BaseActivity {
    private AlbumWallAdapter mAdapter;                   // 适配器
    private LinkedList<YNPhoto> mPhotoDatas;              // 照片墙数据
    private WrapContentGridLayoutManager mGridLayoutManager;
    private YNRecyclerViewAdapter mYNRecyclerViewAdapter;
    private boolean isBottom;
    private RecyclerView rv_home_album;
    private TextView iv_upLoad;
    private ImageView iv_back;
    private boolean isLoad = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer);
        registerBoradcastReceiver();
        initView();
    }

    private void initView() {
        mPhotoDatas = new LinkedList<>();
        rv_home_album = ((RecyclerView) findViewById(R.id.rv_home_album));
        mAdapter = new AlbumWallAdapter(TransferActivity.this, mPhotoDatas, true);
        rv_home_album.setHasFixedSize(true);
        SpacesItemDecoration decoration = new SpacesItemDecoration(3);
        rv_home_album.addItemDecoration(decoration);
        mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(mAdapter);
        rv_home_album.setAdapter(mYNRecyclerViewAdapter);
        //设置布局管理器
        mGridLayoutManager = new WrapContentGridLayoutManager(TransferActivity.this, 3);
        mGridLayoutManager.setSpanSizeLookup(new HeaderSpanSizeLookup((YNRecyclerViewAdapter) rv_home_album.getAdapter(), mGridLayoutManager.getSpanCount()));
        rv_home_album.setLayoutManager(mGridLayoutManager);
        rv_home_album.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                // 已经到底，返回
                if (isBottom) {
                    showToast("到底了");
                    return;
                }
                // 加载中，返回
//                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rv_home_album);
//                if (state == LoadingFooter.State.Loading) {
//                    showToast("正在为您加载下一页");
//                    return;
//                }
                if (isLoad) {
                    showToast("正在为您加载下一页");
                    return;
                }
                // 加载下一页
//                RecyclerViewStateUtils.setFooterViewState(TransferActivity.this, rv_home_album, 30, LoadingFooter.State.Loading, null);
                loadMore();
            }
        });
        noticeServiceInit();
        iv_upLoad = ((TextView) findViewById(R.id.iv_upLoad));
        iv_upLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SelectedImg.mSelectedImage.size() == 0) {
                    showToast("至少选中一张图片");
                    return;
                }
                Intent intent = new Intent(TransferActivity.this, CardSyncUploadActivity.class);
                intent.putExtra(ACTIONs.aType, false);
                intent.putExtra(ACTIONs.aPush, 0);
                intent.putExtra(ACTIONs.aIsOfficial, 0);
                intent.putExtra(ACTIONs.aContent, "");
                intent.putExtra(ACTIONs.upstorage, "");
                intent.putExtra(ACTIONs.upismemorycard, 0);
                intent.putExtra(ACTIONs.uptags, "");
                intent.putExtra(ACTIONs.upaudio, "");
                intent.putExtra(ACTIONs.upmemorytime, getTime());
                intent.putExtra(ACTIONs.upplace, "");
                intent.putExtra(ACTIONs.upaudiotime, "");
                intent.putExtra(ACTIONs.upcoverUrl, "");
                startActivity(intent);
            }
        });
        iv_back = ((ImageView) findViewById(R.id.iv_back));
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(TransferActivity.this, PicWallActivity.class));
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(TransferActivity.this, PicWallActivity.class));
        super.onBackPressed();
    }

    private void loadMore() {
        isLoad = true;
        rv_home_album.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadStatus(false, CommonConstants.YNS_SIGN_LOAD);
            }
        }, 1000);
    }

    public String getTime() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    private void loadStatus(boolean isTop, String type) {
        // 通知后台加载数据
        Intent mIntent = new Intent(TransferActivity.this, AlbumContentService.class);
        mIntent.setAction(ACTIONs.actionAlbumWall);
        mIntent.putExtra(ACTIONs.aNeedType, type);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra(ACTIONs.aLoadId, mAdapter.getIdByDirection(isTop));
        startService(mIntent);
    }

    private void noticeServiceInit() {
        Intent mIntent = new Intent(TransferActivity.this, AlbumContentService.class);
        mIntent.setAction(ACTIONs.actionAlbumWall);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra(ACTIONs.aNeedType, CommonConstants.YNS_SIGN_INITS);
        mIntent.putExtra(ACTIONs.aLoadId, 0);
        startService(mIntent);
    }

    // 注册接收者
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionTransfer);
        myIntentFilter.addAction(ACTIONs.actionSinglePhoto);
        myIntentFilter.addAction(ACTIONs.actionDeleteList);
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        registerReceiver(mWallBroadcastReceiver, myIntentFilter);
    }

    // 分析并执行动作
    BroadcastReceiver mWallBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                //　加载照片墙数据
                case ACTIONs.actionTransfer:
                    List<YNPhoto> photoList = (List<YNPhoto>) intent.getSerializableExtra(ACTIONs.aAddData);
                    String direction = intent.getStringExtra(ACTIONs.aAddDirection);
                    updateView(photoList, direction);
                    photoList.clear();
                    break;
                case ACTIONs.actionSinglePhoto:
                    String PhotoUrl = intent.getStringExtra(ACTIONs.PhotoUrl);
                    for (int i = 0; i < mPhotoDatas.size(); i++) {
                        if (PhotoUrl != null && PhotoUrl.equals(mPhotoDatas.get(i).getUrl())) {
                            mPhotoDatas.remove(i);
                            mAdapter.notifyItemRemoved(i);
                            break;
                        }
                    }
                    break;
                case ACTIONs.actionDeleteList:
                    loadStatus(true, CommonConstants.YNS_SIGN_REFRESH);
                    break;
                case ACTIONs.actionCloseAlbum:
                    finish();
                    break;
            }
        }
    };

    // 更新照片墙
    private void updateView(List<YNPhoto> photoList, String direction) {
        switch (direction) {
            case ACTIONs.aAddTop:
                mAdapter.addItemsFromTop(photoList);
//                rv_home_album.scrollToPosition(0);
                break;
            case ACTIONs.aAddBottom:
                mAdapter.addItemsFromBottom(photoList);
                if (photoList.size() == 0) {
                    isBottom = true;
//                    RecyclerViewStateUtils.setFooterViewState(TransferActivity.this, rv_home_album, 30, LoadingFooter.State.TheEnd, null);
                }
//                else {
//                    RecyclerViewStateUtils.setFooterViewState(rv_home_album, LoadingFooter.State.Normal);
//                }
                break;
        }
        isLoad = false;
    }

    @Override
    protected void onDestroy() {
        SelectedImg.mSelectedImage.clear();
        unregisterReceiver(mWallBroadcastReceiver);
        super.onDestroy();
    }
}
